package com.collectplus.express;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.SerachStationBean;
import com.collectplus.express.self.SelfSerachStationAdapter;
import com.collectplus.express.tools.TextWatcherExt;
import com.shouhuobao.bhi.collectpoint.ServicePointListActivity;

import java.util.ArrayList;

import droid.frame.app.Callback;
import droid.frame.umeng.UMeng;
import droid.frame.utils.android.ImmUtils;
import droid.frame.utils.lang.JsonParser;

/**
 * 带有搜索框的Activity
 *
 * @author coffee<br>
 *         2016-12-5下午3:23:49
 */
public abstract class BaseActivityWithSearch extends BaseActivity2 implements View.OnClickListener {//OnGetPoiSearchResultListener
    private View mTitleLayout;// 顶部TitleLayout
    private EditText mSearchInput;// 搜索输入框
    private TextView mSearchOrCancel;// 搜索按钮(搜索状态显示取消)

    private ListView mListView2;// 搜索结果列表
    // 单击搜索结果列表的item
    private Callback searchCallback;
    // 切换搜索视图
    private Callback searchSwitch;
    private boolean autoSearch;
    //    private PoiSearch mPoiSearch;
    public String mCurrentCityName = "";

    @Override
    @SuppressLint("ResourceAsColor")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        mPoiSearch = PoiSearch.newInstance();
//        mPoiSearch.setOnGetPoiSearchResultListener(this);
    }

    @Override
    protected void findViewById() {
        super.findViewById();
        mTitleLayout = findViewById(R.id.app_title_layout);
        mListView2 = (ListView) findViewById(R.id.listview2);
        //
        mSearchInput = (EditText) findViewById(R.id.search_edit_input);
        mSearchInput.clearFocus();
        mSearchInput.setFocusable(false);
        mSearchInput.setFocusableInTouchMode(false);
        mSearchInput.setOnClickListener(this);
        mSearchOrCancel = (TextView) findViewById(R.id.search_cancel);
        mSearchOrCancel.setOnClickListener(this);

        // mSearchInput.setImeActionLabel("搜索", EditorInfo.IME_ACTION_SEARCH);
        mSearchInput.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mSearchInput.addTextChangedListener(new TextWatcherExt() {
            private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 99999) {
                        String keywords = mSearchInput.getText().toString();
                        if (isEmpty(keywords)) {
                            // ignore
                        } else {
                            autoSearch = true;
                            UMeng.click(getContext(), "self_servicePoint_search_click");
                            showLoadingDialog(null);
                            AppHttp.getInstance().serachNearStation(mCurrentCityName, keywords);
//                            mPoiSearch.searchInCity((new PoiCitySearchOption()).city(mCurrentCityName) //
//                                    .keyword(keywords).pageNum(1).pageCapacity(20));
                        }
                    }
                }
            };

            @Override
            public void afterTextChanged(Editable s) {
                handler.removeMessages(99999);
                handler.sendEmptyMessageDelayed(99999, 1000);
            }
        });
        mSearchInput.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String keywords = mSearchInput.getText().toString();
                    if (isEmpty(keywords)) {
                        // ignore
                    } else {
                        autoSearch = false;
                        showLoadingDialog(null);
                        AppHttp.getInstance().serachNearStation(mCurrentCityName, keywords);
//                        mPoiSearch.searchInCity((new PoiCitySearchOption()).city(mCurrentCityName) //
//                                .keyword(keywords).pageNum(1).pageCapacity(20));
                    }
                    return true;
                }
                return false;
            }
        });
    }

//    @Override
//    public void onGetPoiDetailResult(PoiDetailResult arg0) {
//
//    }

//    @Override
//    public void onGetPoiResult(PoiResult result) {
//        if (result == null || result.getAllPoi() == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
//            showToast("搜索结果为空");
//            return;
//        }
//        List<PoiInfo> allPois = result.getAllPoi();
//        if (allPois != null && allPois.size() > 0) {
//            ArrayList<PoiBean> items = new ArrayList<PoiBean>();
//            for (PoiInfo poi : allPois) {
//                PoiBean item = new PoiBean();
//                item.address = poi.name;
//                item.latitude = poi.location.latitude;
//                item.longitude = poi.location.longitude;
//                items.add(item);
//            }
//            //
//            ArrayAdapter<PoiBean> adapter = new ArrayAdapter<PoiBean>(getContext(), android.R.layout.simple_dropdown_item_1line, items) {
//            };
//            mListView2.setAdapter(adapter);
//            mListView2.setOnItemClickListener(new OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                    PoiBean item = (PoiBean) parent.getItemAtPosition(position);
//                    if (searchCallback != null) {
//                        searchCallback.execute(item);
//                    }
//                    // 切换视图
//                    onClick(mSearchOrCancel);
//                }
//            });
//            // 搜索完成以后隐藏软键盘
//            if (autoSearch) {
//                // 通过联想搜索 不收键盘
//            } else {// 点击搜索 收起键盘
//                getHandler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        ImmUtils.hide(getContext());
//                    }
//                }, 200);
//            }
//        } else {
//            // mSearchInput.setAdapter(null);
//        }
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 搜索框
            case R.id.search_edit_input:
                // 非"搜索"状态下点击搜索框--切换到搜索状态
                if (mSearchOrCancel.getTag() == null) {
                    if (searchSwitch != null) {
                        searchSwitch.execute(true);
                    }
                    hideOrShowBanner(false);
                    mSearchOrCancel.setVisibility(View.VISIBLE);
                    mSearchOrCancel.setTag("");//
                    mSearchOrCancel.setText("取消");
                    mTitleLayout.setVisibility(View.GONE);
                    mListView2.setVisibility(View.VISIBLE);
                    getHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSearchInput.setFocusable(true);
                            mSearchInput.setFocusableInTouchMode(true);
                            mSearchInput.requestFocus();
                            ImmUtils.show(getContext(), mSearchInput);
                        }
                    }, 500);
                } else {
                    // 搜索状态点击, 不作处理
                }
                break;
            // 取消
            case R.id.search_cancel:
                if (searchSwitch != null) {
                    searchSwitch.execute(false);
                }
                if (mSearchOrCancel.getTag() == null) {
                    // 非搜索状态, 点击搜索按钮不做处理
                } else {
                    hideOrShowBanner(true);
                    // 取消
                    mSearchOrCancel.setTag(null);//
                    mSearchOrCancel.setText("搜索");
                    mSearchOrCancel.setVisibility(View.GONE);
                    mTitleLayout.setVisibility(View.VISIBLE);
                    mListView2.setVisibility(View.GONE);
                    mListView2.setAdapter(null);
                    getHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSearchInput.setFocusable(false);
                            mSearchInput.setFocusableInTouchMode(false);
                            mSearchInput.clearFocus();
                            ImmUtils.hide(getContext());
                        }
                    }, 200);
                }
                break;
        }
    }
    protected void hideOrShowBanner(boolean isShow){

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (mPoiSearch != null) {
//            mPoiSearch.destroy();
//        }
    }

    public void setSearchCallback(Callback searchCallback) {
        this.searchCallback = searchCallback;
    }

    public void setSearchSwitch(Callback searchSwitch) {
        this.searchSwitch = searchSwitch;
    }

//    @Override
//    public void onGetPoiIndoorResult(PoiIndoorResult arg0) {
//        // TODO Auto-generated method stub
//
//    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //根据关键字搜索附近驿站
            case MsgID.serach_station_for_keywords:
                cancelLoadingDialog();
                if (isEmpty(msg.obj)){
                    showToast("搜索结果为空");
                    return false;
                }
                final SerachStationBean bean = JsonParser.parse(msg.obj + "", SerachStationBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (bean.getStatus() == 0) {
                            SelfSerachStationAdapter adapter = null;
                            if (bean.getResults() != null && bean.getResults().size() > 0) {
                                if (bean.getResults().size() == 1) {
                                    adapter = new SelfSerachStationAdapter(null,getContext());
                                    mListView2.setAdapter(adapter);
                                    showToast("搜索结果为空");
                                } else {
                                    adapter = new SelfSerachStationAdapter((ArrayList<SerachStationBean.ResultsBean>) bean.getResults(), getContext());
                                    mListView2.setAdapter(adapter);
                                    mListView2.setOnItemClickListener(new OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            SerachStationBean.ResultsBean item = (SerachStationBean.ResultsBean) parent.getItemAtPosition(position);
                                            if (item == null) {
                                                return;
                                            }
                                            if (searchCallback != null) {
                                                searchCallback.execute(item);
                                            }
                                            // 切换视图
                                            onClick(mSearchOrCancel);
                                        }
                                    });
                                    if (autoSearch) {
                                        // 通过联想搜索 不收键盘
                                    } else {// 点击搜索 收起键盘
//                                        getHandler().postDelayed(new Runnable() {
//                                            @Override
//                                            public void run() {
//                                                ImmUtils.hide(getContext());
//                                            }
//                                        }, 200);
                                    }
                                }
                            } else {
                                adapter = new SelfSerachStationAdapter(null,getContext());
                                mListView2.setAdapter(adapter);
                                showToast("搜索结果为空");
                            }
                        } else {
                            showToast(bean.getMessage());
                        }
                    }
                });
                return false;
            default:
                return super.handleMessage(msg);
        }
    }
}
